<template>
  <div>
    <div class="grid grid-cols-6 h-screen bg-white">
      <!-- 左边栏 -->
      <div class="col-span-6 md:col-span-3 sm:col-span-6">
        <div class="login-container-left flex justify-center items-center flex-col">
          <div class="animate__animated animate__bounceInLeft items-center flex flex-col">
            <h2 class="font-bold text-4xl mb-7 text-white">Mindsparkle 博客{{ isLogin ? '登录' : '注册' }}</h2>
            <p class="text-white">"欢迎来到 Mindsparkle！✨开始书写你的星火，或静待一场思维的烟火吧！🎇"</p>
            <img :src="currentImage" class="login-image" />
          </div>
        </div>
      </div>
      <!-- 右边栏 -->
      <div class="col-span-6 px-3 md:col-span-3 sm:col-span-6">
        <div
            class="login-container-right flex justify-center items-center flex-col animate__animated animate__bounceInRight animate__fast"
        >
          <h2 class="font-bold text-3xl text-gray-800 mt-5">{{ isLogin ? '欢迎回来' : '创建账号' }}</h2>
          <div class="flex items-center justify-center my-5 text-gray-400 space-x-2">
            <span class="h-[1px] w-16 bg-gray-200"></span>
            <span>{{ isLogin ? '账号密码登录' : '账号密码注册' }}</span>
            <span class="h-[1px] w-16 bg-gray-200"></span>
          </div>
          <div>
            <el-form ref="formRef" :rules="rules" :model="form" class="w-[300px]">
              <el-form-item prop="username">
                <el-input
                    v-model="form.username"
                    :prefix-icon="User"
                    :placeholder="isLogin ? '请输入用户名' : '请输入手机号'"
                    size="large"
                    clearable
                />
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                    v-model="form.password"
                    type="password"
                    autocomplete="off"
                    :prefix-icon="Lock"
                    placeholder="请输入密码"
                    show-password
                    size="large"
                    clearable
                />
              </el-form-item>
              <el-form-item v-if="!isLogin" prop="confirmPassword">
                <el-input
                    v-model="form.confirmPassword"
                    type="password"
                    autocomplete="off"
                    :prefix-icon="Lock"
                    placeholder="请确认密码"
                    show-password
                    size="large"
                    clearable
                />
              </el-form-item>
              <!-- 在密码输入下方显示错误提示 -->
              <div v-if="errorMessage" class="mt-1 text-xs" style="color: red;">
                {{ errorMessage }}
              </div>
              <el-form-item>
                <el-button
                    round
                    type="primary"
                    @click="onSubmit"
                    :loading="loading"
                    class="w-[300px] login-btn mt-4"
                    size="large"
                >
                  {{ isLogin ? '登 录' : '注 册' }}
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button
                    round
                    type="default"
                    @click="toggleMode"
                    class="w-[300px] register-btn mt-2"
                    size="large"
                >
                  {{ isLogin ? '注册账号' : '已有账号？登录' }}
                </el-button>
              </el-form-item>
              <!-- 角色切换按钮 -->
              <div class="flex justify-center mt-4">
                <div class="role-switch-container">
                  <div class="role-switch" :class="{'switch-admin': isAdmin}">
                    <div class="role-switch-slider" @click="toggleRole">
                      <span class="role-text user" :class="{'active': !isAdmin}">用户</span>
                      <span class="role-text admin" :class="{'active': isAdmin}">管理员</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref, onMounted, onBeforeUnmount} from 'vue'
import {login} from '@/api/admin/user'
import {registerUser} from '@/api/user/register'
import {useRouter} from 'vue-router'
import {useStore} from 'vuex'
import {setToken} from '@/composables/auth'
import {User, Lock} from '@element-plus/icons-vue'
import developerImg from '@/assets/developer.png'
import loginLogoImg from '@/assets/login-logo.png'
import { showMessage } from '@/composables/util'

const router = useRouter()
const store = useStore()
const currentImage = ref(developerImg)
const isAdmin = ref(false)
const isLogin = ref(true)

const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
})

const errorMessage = ref('')

const rules = {
  username: [
    {
      required: true,
      message: isLogin.value ? '用户名不能为空' : '手机号不能为空',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认密码',
      trigger: 'blur'
    }
  ]
}

const formRef = ref(null)
const loading = ref(false)

const onSubmit = () => {
  errorMessage.value = ''
  formRef.value.validate((valid) => {
    if (!valid) {
      console.log('验证不通过')
      return false
    }
    
    if (!isLogin.value && form.password !== form.confirmPassword) {
      errorMessage.value = '两次输入的密码不一致'
      return
    }

    loading.value = true
    const role = isAdmin.value ? 1 : 2

    if (isLogin.value) {
      // 登录逻辑
      login(form.username, form.password, role)
          .then(res => {
            if (res.success === true) {
              errorMessage.value = ''
              console.log('登录成功，响应数据:', res.data)
              setToken(res.data.token)
              console.log('Token已存储:', res.data.token)
              localStorage.setItem('role', role)
              if (!isAdmin.value) {
                router.push('/user')
              } else {
                router.push('/admin')
              }
            } else {
              errorMessage.value = "账户或密码错误"
            }
          })
          .catch(err => {
            errorMessage.value = "账户或密码错误"
          })
          .finally(() => {
            loading.value = false
          })
    } else {
      // 注册逻辑
      registerUser({
        username: form.username,
        password: form.password,
      })
          .then((res) => {
            // 检查响应是否包含成功标志
            if (res && res.success === false) {
              errorMessage.value = '该手机号已被注册，请使用其他手机号'
              return
            }
            showMessage('注册成功', 'success')
            isLogin.value = true
            form.confirmPassword = ''
          })
          .catch((error) => {
            // 假设接口返回的错误信息包含手机号已存在的信息
            errorMessage.value = '该手机号已被注册，请使用其他手机号'
            console.error('注册失败:', error)
          })
          .finally(() => {
            loading.value = false
          })
    }
  })
}

const toggleMode = () => {
  isLogin.value = !isLogin.value
  errorMessage.value = ''
  form.confirmPassword = ''
}

function onKeyUp(e) {
  console.log(e)
  if (e.key === 'Enter') {
    onSubmit()
  }
}

const toggleRole = () => {
  isAdmin.value = !isAdmin.value
  currentImage.value = isAdmin.value ? loginLogoImg : developerImg
}

// 添加键盘监听
onMounted(() => {
  document.addEventListener('keyup', onKeyUp)
})

// 移除键盘监听
onBeforeUnmount(() => {
  document.removeEventListener('keyup', onKeyUp)
})
</script>

<style>
:deep([type='text']:focus) {
  border-color: transparent !important;
}

.login-container {
  height: 100vh;
  width: 100%;
  background-color: #fff;
}

.login-container-left {
  height: 100%;
  background: #001428;
  color: #fff;
}

.login-container-right {
  height: 100%;
}

.login-image {
  /* 可根据需要调整 */
  height: 450px;
}

/* 滑动按钮样式 */
.role-switch-container {
  display: flex;
  justify-content: center;
  width: 240px;
}

.role-switch {
  position: relative;
  width: 240px;
  height: 40px;
  background-color: #f0f0f0;
  border-radius: 20px;
  padding: 4px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.role-switch-slider {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  transition: all 0.3s ease;
}

.role-switch-slider::before {
  content: '';
  position: absolute;
  width: 50%;
  height: 100%;
  background: #67c23a;
  border-radius: 16px;
  left: 0;
  transition: all 0.3s ease;
  z-index: 1;
}

.switch-admin .role-switch-slider::before {
  left: 50%;
  background: #409eff;
}

.role-text {
  flex: 1;
  text-align: center;
  color: #909399;
  font-weight: 500;
  z-index: 2;
  transition: all 0.3s ease;
}

.role-text.active {
  color: #fff;
}

.role-text.user {
  padding-left: 10px;
}

.role-text.admin {
  padding-right: 10px;
}
</style>
